﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections;
using Telerik.Windows.Controls;
using TestMatrix.Model;
using TestMatrix.BLController;

namespace TestMatrix.Phone
{
    public class RadDataListBoxBase : PhoneApplicationPage
    {
        private IEnumerable itemsSource;
        private bool isDisplayed;

        private RadDataBoundListBox DataBoundListBox;
        public RadDataListBoxBase(RadDataBoundListBox _DataBoundListBox)
        {
            this.DataBoundListBox = _DataBoundListBox;
        }

        protected virtual RadDataBoundListBox ListBox
        {
            get { return this.DataBoundListBox; }
        }

        public bool IsDisplayed
        {
            get { return this.isDisplayed; }
        }

        protected virtual void OnDisplayed()
        {
            if (this.ListBox==null)
            {
                return;
            }
            if (this.itemsSource == null)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(this.LoadItemsSource);
            }
            else
            {
                this.DisplayData(this.itemsSource);
            }
        }

        private void LoadItemsSource(object state)
        {
            this.itemsSource = this.CreateItemsSource();
            if (this.isDisplayed)
            {
                this.DisplayData(this.itemsSource);
            }

        }

        protected virtual IEnumerable CreateItemsSource()
        {
            return null;
        }
        protected virtual bool EnableAsyncBalance
        {
            get
            {
                return true;
            }
        }

        protected virtual void DisplayData(IEnumerable items)
        {
            if (this.ListBox == null || !this.isDisplayed)
            {
                return;
            }

            this.Dispatcher.BeginInvoke(() =>
            {
                this.ListBox.BeginAsyncBalance();
                this.ListBox.ItemsSource = items;
                this.OnItemsBound();

            });
        }

        protected virtual void OnItemsBound()
        {
        }
    }
}
